/*
 *@本js功能：制作课程
 *@本js作者：杨锡君
 *@编写时间：2017年11月2日
 */
$(function() {
	var Alert1 = new Alert();
	var confirm1 = new Confirm();
	var loading1 = new Loading();
	loading1.init();
	var $profession = $("#profession");   
	var $direct = $("#direct");
	var $courseName = $("#courseName");
	var $saveCourseInfo = $(".saveCourseInfo");
	var $courseScore = $("#courseScore");
	var $courseNum = $("#courseNum");
	var $makeTeacher = $("#makeTeacher");
	var $courseShort = $("#courseShort");
	var $saveChapter = $(".saveChapter");
	var $myCourseNameLeft = $(".myCourseNameLeft");
	var $resetChapter = $(".resetChapter");
	//预置课程章节列表
	function preModel(opt){
		var str =  "<li class=\"dd-item\" data-courseid="+ opt.courseId +">"
				+"<div class=\"dd-handle\"  style=\"background: #fff url(pc/images/ico_folder.png) no-repeat left 12.4% bottom;height: 37px;\">"+ opt.courseName +"</div>"
				+"<ol class=\"dd-list\">";
				var str1 = "";
			$.map(opt.chapterList, function(obj) {
                if(obj.courseMark!=undefined&&obj.courseMark!=null && obj.courseMark!=''){
                    str1 += "<li class=\"dd-item\" data-coursemark='"+ obj.courseMark +"' data-chaptername="+ obj.chapterName +" data-chapterid="+ obj.chapterId +">"
                        +"<div title='"+ obj.chapterName +obj.courseMark +"' class=\"dd-handle\"><i></i>"+ obj.chapterName +'<b style="color:#adafb0;font-size: 10px;">&emsp;'+ obj.courseMark +'</b>'+"</div>"
                        +"</li>";
                }else{
                    str1 += "<li class=\"dd-item\"  data-chaptername="+ obj.chapterName +" data-chapterid="+ obj.chapterId +">"
                        +"<div title='"+ obj.chapterName +"' class=\"dd-handle\"><i></i>"+ obj.chapterName +"</div>"
                        +"</li>";
                }
			});
		var str2 = 	"</ol></li>";
		return str + str1 + str2;
	}
    function preModels(opt){
        var str =  "<li class=\"dd-item\" data-courseid="+ opt.courseId +">"
            +"<div class=\"dd-handle\"  style=\"background: #fff url(pc/images/ico_folder.png) no-repeat left 12.4% bottom;height: 37px;\">"+ opt.courseName +"</div>"
            +"<ol class=\"dd-list\">";
        var str1 = "";
        $.map(opt.chapterList, function(obj) {
            if(obj.courseMark!=undefined&&obj.courseMark!=null && obj.courseMark!=''){
                str1 += "<li class=\"dd-item\" data-coursemark='"+ obj.courseMark +"' data-chaptername="+ obj.chapterName +" data-chapterid="+ obj.chapterId +">"
                    +"<div title='"+ obj.chapterName +obj.courseMark +"' class=\"dd-handle\"><i></i>"+ obj.chapterName +'<b style="color:#adafb0;font-size: 10px;">&emsp;'+ obj.courseMark +'</b>'+"</div>"
                    +"</li>";
            }else{
                str1 += "<li class=\"dd-item\"  data-chaptername="+ obj.chapterName +" data-chapterid="+ obj.chapterId +">"
                    +"<div title='"+ obj.chapterName +"' class=\"dd-handle\"><i></i>"+ obj.chapterName +"</div>"
                    +"</li>";
            }
        });
        var str2 = 	"</ol></li>";
        return str + str1 + str2;
    }
	//自定义章节列表
	// function customModel(opt){
	// 	return 	"<li class=\"dd-item\" data-chaptername="+ opt.chapterName +"  data-chapterid="+ opt.chapterId +">"
	// 			+"<div class=\"dd-handle\"><i></i>"+ opt.chapterName +"</div>"
	// 			+"</li>";
	// }
    function customModel(opt){
        var str =  "<li class=\"dd-item\" >"
            +"<div class=\"dd-handle\"  style=\"background: #fff url(pc/images/ico_folder.png) no-repeat left 12.4% bottom;height: 37px;\">自定义课程</div>"
            +"<ol class=\"dd-list\">";
        var str1 = "";
        $.map(opt, function(obj) {
            if(obj.courseMark!=undefined&&obj.courseMark!=null && obj.courseMark!=''){
                str1 += "<li class=\"dd-item\" data-coursemark='"+ obj.courseMark +"' data-chaptername="+ obj.chapterName +" data-chapterid="+ obj.chapterId +">"
                    +"<div title='"+ obj.chapterName +obj.courseMark +"' class=\"dd-handle\"><i></i>"+ obj.chapterName +'<b style="color:#adafb0;font-size: 10px;">&emsp;'+ obj.courseMark +'</b>'+"</div>"
                    +"</li>";
            }else{
                str1 += "<li class=\"dd-item\"  data-chaptername="+ obj.chapterName +" data-chapterid="+ obj.chapterId +">"
                    +"<div title='"+ obj.chapterName +"' class=\"dd-handle\"><i></i>"+ obj.chapterName +"</div>"
                    +"</li>";
            }
        });
        var str2 = 	"</ol></li>";
        return str + str1 + str2;
    }
	var courseMake = {
        oldList:[],
		init: function() {
			this.bindEvent();
            maxLengthLimit.init("publicText");
		},
		bindEvent: function() {
			var self = this;
			self.courseTypeTap();
			self.getData();
			$saveCourseInfo.off("click").click(function(){
				var flag = self.verifications();
				if(flag){
					self.addCourse();
				}
			});
			//保存章节
			$saveChapter.off("click").click(function(){
				self.addChapterList();
			});
            $("#courseShort").off("keyup").keyup(function () {
                $(".long").html($("#courseShort").val().length);
            });
            $(".looktg").off("click").click(function () {
                var json = JSON.stringify({
                    "pageName": $(this).attr("data-url"),
                    "paramData": {
                        "some": result.paramData.some
                    }
                });
                window.location.href = "skipPage?jsonStr=" + json;
            });
		},
		addChapterList:function(){
        	var self = this;
			//保存章节
			if($myCourseNameLeft.html() != $courseName.val()){
					Alert1.content = "课程名称已修改,请先保持修改课程信息";
					Alert1.init();
					Alert1.show();
					return false;
				}
				var list = [];
				for(var i = 0;i < $("#nestable>ol>li").length;i++){
					if($("#nestable>ol>li").eq(i).attr("data-coursemark") != undefined){
                        list.push({"chapterId": Number($("#nestable>ol>li").eq(i).attr("data-chapterid")),"chapterNum":(i+1),"courseMark":$("#nestable>ol>li").eq(i).attr("data-coursemark")})

                    }else{
                        list.push({"chapterId": Number($("#nestable>ol>li").eq(i).attr("data-chapterid")),"chapterNum":(i+1)})

                    }
				}
				var jsonStr = JSON.stringify({
					"courseId":$myCourseNameLeft.attr("data-courseid"),
					"chapterList":list,
					"oldList":self.oldList
				});
				loading1.show();
				$.ajax({
					type:"post",
					url:"addCourseReChapters",
					async:true,
					data:{
						"jsonStr":jsonStr
					},
					success:function(msg){
						loading1.hide();
						msg = JSON.parse(msg);
						if(msg.result == "success"){
							Alert1.content = "修改课程成功";
							Alert1.success = function(){
								var json = JSON.stringify({
									"pageName":"preserveCourse"
								});
								window.location.href = "skipPage?jsonStr="+json;
							};
							Alert1.init();
							Alert1.show();
							return false;
						}else{
                            Alert1.content = msg.failMsg;
                            Alert1.init();
                            Alert1.show();
						}
					}
				});
		},
		addCourse:function(){
//			提交做好的课程信息 上半部分的提交
			var jsonStr = JSON.stringify({
                "courseId":result.paramData.courseId,
				"courseCredit":Number($courseScore.val()),
				"courseIntroduction":$courseShort.val(),
				"courseName":$courseName.val(),
				"professionId":Number($profession.val()),
				"maxStu":Number($courseNum.val()),
				"mainId":Number($direct.val())
			});
			loading1.show();
			$.ajax({
				type:"post",
				url:"saveCourse",
				async:true,
				data:{
					"jsonStr":jsonStr
				},
				success:function(msg){
					loading1.hide();
					msg =JSON.parse(msg);
					if(msg.result == "success"){
						Alert1.content = "课程信息保存成功";
						Alert1.success = function () {
                            $myCourseNameLeft.html($courseName.val());
                            $myCourseNameLeft.attr("data-courseid",msg.courseId);
                        };
						Alert1.init();
						Alert1.show();
					}else{
						if(msg.failMsg!=undefined){
                            Alert1.content = msg.failMsg;
						}else{
                            Alert1.content = "保存失败";
						}

                        Alert1.init();
                        Alert1.show();
					}
				}
			});
		},
		verifications:function(){
			var courseName = $courseName.val();
			var flag = verification.spaceCode(courseName);
			var flags = verification.specialCode(courseName);
			var courseScore = $courseScore.val();
			var flages = verification.numberCode(courseScore);
			var courseNum = $courseNum.val();
			var flg = verification.numberCode(courseNum);
			var makeTeacher = $makeTeacher.val();
			var flgs = verification.spaceCode(makeTeacher);
			var flges = verification.specialCode(makeTeacher);
			var courseShort = $courseShort.val();
			var fls = verification.spaceCode(courseShort);
			var fles = verification.specialCode(courseShort);
			if(courseName == ""){
				Alert1.content = "请输入课程名称";
				Alert1.init();
				Alert1.show();
				return false;
			}
			if(flag != true) {
				Alert1.content = "课程名称"+flag;
				$courseName.val("");
				Alert1.init();
				Alert1.show();
				return false;
			}
			if(flags != true) {
				Alert1.content = "课程名称"+flags;
				$courseName.val("");
				Alert1.init();
				Alert1.show();
				return false;
			}
			if(courseScore == ""){
				Alert1.content = "请输入课程学分";
				Alert1.init();
				Alert1.show();
				return false;
			}
            if(courseScore == 0){
                Alert1.content = "课程学分不能为0";
                Alert1.init();
                Alert1.show();
                return false;
            }
			if(flages != true) {
				Alert1.content = "课程学分"+flages;
				$courseScore.val("");
				Alert1.init();
				Alert1.show();
				return false;
			}
			if($profession.val() == 0){
				Alert1.content = "请选择专业";
				Alert1.init();
				Alert1.show();
				return false;
			}
			if(courseNum == ""){
				Alert1.content = "请输入课程人数";
				Alert1.init();
				Alert1.show();
				return false;
			}
            if(courseNum == 0){
                Alert1.content = "课程人数不能为0";
                Alert1.init();
                Alert1.show();
                return false;
            }
			if(flg != true) {
				Alert1.content = "请正确输入课程人数";
				$courseNum.val("");
				Alert1.init();
				Alert1.show();
				return false;
			}
			if($direct.val() == 0){
				Alert1.content = "请选择专业方向";
				Alert1.init();
				Alert1.show();
				return false;
			}
			if(makeTeacher == ""){
				Alert1.content = "请输入制作教师";
				Alert1.init();
				Alert1.show();
				return false;
			}
			if(flgs != true) {
				Alert1.content = "制作教师"+flgs;
				$makeTeacher.val("");
				Alert1.init();
				Alert1.show();
				return false;
			}
			if(flges != true) {
				Alert1.content = "制作教师"+flges;
				$makeTeacher.val("");
				Alert1.init();
				Alert1.show();
				return false;
			}
			if(courseShort != ""){
                if(fls != true) {
                    Alert1.content = "课程简介"+fls;
                    Alert1.init();
                    Alert1.show();
                    return false;
                }
                if(fles != true) {
                    Alert1.content = "课程简介"+fles;
                    Alert1.init();
                    Alert1.show();
                    return false;
                }
			}

			return true;
		},
		getData:function(){
			//获取初始数据
			var self = this;
			var jsonStr = JSON.stringify({
				"courseId":result.paramData.courseId
			});
			loading1.show();
			$.ajax({
				type:"post",
				url:"skipSaveCourse",
				async:true,
				data:{
					"jsonStr":jsonStr
				},
				success:function(msg){
					loading1.hide();
					msg = JSON.parse(msg);
					$.map(msg.professionList, function(opt) {
						$profession.append("<option value="+ opt.professionId +">"+ opt.professionName +"</option>");
					});
					$courseName.val(msg.course.courseName);
					$courseName.attr("data-courseid",msg.course.courseId);
					$courseScore.val(msg.course.courseCredit);
					$profession.val(msg.course.professionId);
					$courseNum.val(msg.course.maxStu);
					$makeTeacher.val(msg.userName);
					$courseShort.val(msg.course.courseIntroduction);
					$(".long").html(msg.course.courseIntroduction.length);
//					章节头部名称获取
					$myCourseNameLeft.html(msg.course.courseName);
					$myCourseNameLeft.attr("data-courseid",msg.course.courseId);
					
//					章节列表数据获取
					if(msg.chapterList.length != 0){
						$("#nestable").empty();
						var str = "<ol class=\"dd-list\">";
						var str1 = "";
						var str2 = "</ol>";
						$.map(msg.chapterList, function(opt) {
							if(opt.courseMark != undefined && opt.courseMark != null && opt.courseMark != ''){
                                str1 += "<li title='"+ opt.chapterName +opt.courseMark +"' class=\"dd-item\" data-coursemark='"+ opt.courseMark +"' data-chaptername="+ opt.chapterName +" data-chapterid="+ opt.chapterId +"><div class=\"dd-handle\"><i></i>"+ opt.chapterName +'<b style="color:#adafb0;font-size: 10px;">&emsp;'+ opt.courseMark +'</b>'+"</div></li>";
                            	self.oldList.push(opt.chapterId);
							}else{
                                str1 += "<li title='"+ opt.chapterName +opt.courseMark +"' class=\"dd-item\" data-chaptername="+ opt.chapterName +" data-chapterid="+ opt.chapterId +"><div class=\"dd-handle\"><i></i>"+ opt.chapterName +"</div></li>";
                            }
						});
						$("#nestable").append(str+str1+str2);
					}else{
						$("#nestable").html("<div class=\"dd-empty\"></div>");
					}
					
					
					//获取该专业下的专业方向
					var json = JSON.stringify({
					"professionId":Number(msg.course.professionId)
					});
					var mainIds = msg.course.mainId;
					$.ajax({
						type:"post",
						url:"getMyProCourseList",
						async:true,
						data:{
							"jsonStr":json
						},
						success:function(msg){
							msg = JSON.parse(msg);
							$direct.empty();
							$direct.append("<option value='0'>请选择</option>");
							if(msg.directList.length!=0){
                                $.map(msg.directList, function(opt) {
                                    $direct.append("<option value="+ opt.mainId +">"+ opt.directName +"</option>");
                                });
                                $direct.val(mainIds);
							}
						}
				});
				}
			});
			//专业专业方向联动
			$profession.off("change").change(function(){
				var json = JSON.stringify({
					"professionId":Number($(this).val())
				});
				$.ajax({
					type:"post",
					url:"getMyProCourseList",
					async:true,
					data:{
						"jsonStr":json
					},
					success:function(msg){
						msg = JSON.parse(msg);
						$direct.empty();
						$direct.append("<option value='0'>请选择</option>");
						if(msg.directList.length!=0){
                            $.map(msg.directList, function(opt) {
                                $direct.append("<option value="+ opt.mainId +">"+ opt.directName +"</option>");
                            });
						}
					}
				});
			});
            self.getCourseData();
		},
        getCourseData:function () {
            var self= this;
            //获取课程章节列表
            $.ajax({
                type:"post",
                url:"getAfterSaveChapter",
                async:true,
                success:function(msg){
                    msg = JSON.parse(msg);
                    var str = "";
                    var strs = "";
                    if(msg.result == "success"){
                        if(msg.myChapterList.length!=0){
                            // var str = "<li class=\"dd-item\" data-id=\"15\">"
                            //     +"<div class=\"dd-handle\">自定义课程</div>"
                            //     +"<ol class=\"dd-list customCourseList\" >";
                            //
                            // var str2 ="</ol>"
                            //     +"</li>";
                            var strs = customModel(msg.myChapterList);
                            // $.each(msg.myChapterList, function(key) {
                            //     strs +=
                            //
                            // });
                            $(".customCourse").append(strs);
                        }
                        if(msg.courseList.length!=0){
                            $.each(msg.courseList, function(key) {
                                str += preModels(this);
                            });
                            $(".customCourse").append(str);

                            // $(".presetCourse").append(str);
                        }

                        // $(".customCourseList").append(str + strs);
                        $.ajax({
                            type:"post",
                            url:"skipAddCourse",
                            async:true,
                            success:function(msg){
                                msg = JSON.parse(msg);
                                var str = "";
                                if(msg.result == "success"){
                                    if(msg.courseList.length!=0){
                                        $.map(msg.courseList, function(opt) {
                                            str += preModel(opt);
                                        });
                                        $(".presetCourse").append(str);
                                    }

                                }
                                self.nestables();
                                var htm = $("#nestable2").html();
//			刷新
                                $resetChapter.off("click").click(function(){
                                    confirm1.content = "确定刷新预置课程和自定义课程吗？";
                                    confirm1.success = function(){
                                        $("#nestable2").html(htm)
                                        // $(".presetCourse").html("");
                                        // $(".customCourse").html("");
                                        $(".presetCourse").show();
                                        $(".customCourse").hide();
                                        $(".ownChapterListTitle>li:nth-of-type(1)").attr("data-value","1").siblings("li").attr("data-value","0");
                                    };
                                    confirm1.init();
                                    confirm1.show();
                                });
                            }
                        });
                    }

                }
            });

        },
		courseTypeTap:function(){
//			切换
			$(".ownChapterListTitle").children("li").off("click").click(function(){
				var name = $(this).attr("data-name");
				$(this).attr("data-value","1").siblings("li").attr("data-value","0");
				
				if(name == "preset"){
					$(".presetCourse").show();
					$(".customCourse").hide();
				}
				if(name == "custom"){
					$(".presetCourse").hide();
					$(".customCourse").show();
                    $("#nestable2").children("button").eq(0).show();
                    $("#nestable2").children("button").eq(1).hide();
				}
			});
		},
		nestables: function() {
			//拖拽插件
			$("body").append("<script src=\"pc/js/extends/jquery.nestableS.js\"></script>");
			var updateOutput = function(e){

			};
			// activate Nestable for list 1
			$('#nestable').nestable({
					group: 1
			}).on('change', updateOutput);

			// activate Nestable for list 2

			$('#nestable2').nestable({
					group: 1
			}).on('change', updateOutput);
            $('#nestable3').nestable({
                group: 1
            }).on('change', updateOutput);
			// output initial serialised data
			updateOutput($('#nestable').data('output', $('#nestable-output')));
			updateOutput($('#nestable2').data('output', $('#nestable2-output')));
            updateOutput($('#nestable3').data('output', $('#nestable-output')));
//			下拉及序号
			setInterval(function() {
				$("button").off("click").click(function() {
					var actions = $(this).attr("data-action");
					if(actions == "collapse") {
						$(this).hide().siblings("button").show();
						$(this).siblings("ol").hide();
					}
					if(actions == "expand") {
						$(this).hide().siblings("button").show();
						$(this).siblings("ol").show();
					}

				});
				for(var i = 0;i<$(".myChapterList i").length;i++){
					$(".myChapterList i").eq(i).html("第<em>"+(i+1)+"</em>章");
				}
                $("#nestable>ol>li").children("div[style*='background']").parent().remove();
				
			}, 100);
		}
	};
	courseMake.init();
});